package com.tjl.foodapp;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Optional;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FoodListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FoodListFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FoodListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FoodListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FoodListFragment newInstance(String param1, String param2) {
        FoodListFragment fragment = new FoodListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    //页面元素
ImageButton btn_back_head,btn_like_head;
    TextView tx_shopname_head;
    RecyclerView rv_foodlist_center;
    //上下文
    Context context;
    //请求队列
    RequestQueue queue;
    //子页面管理器
    FragmentManager manager;
    // 数据源
    ArrayList<Food> list = new ArrayList<Food>();
    int shop_id =0;
    //店铺ID
    //前一页面
    String prePage = "";
    ImageButton btn_cart;
    //适配器类
    class MyAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =  LayoutInflater.from(context).inflate(R.layout.food_item,null);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ViewHolder viewHolder = (ViewHolder)holder;
            Food food = list.get(position);
            viewHolder.tx_foodname_price_fooditem.setText(food.getFoodname()+" "+food.getPrice()+"元");
            viewHolder.tx_intro_fooditem.setText(food.getIntro());

            getImageByURL(Utils.urlBase+"image/"+food.getPic()+".jpg"
                    ,viewHolder.img_food_fooditem);
            viewHolder.img_food_fooditem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("shop_id",shop_id);
                    bundle.putInt("food_id",food.getFood_id());
                    bundle.putString("prePage","foodlist");
                    changeFragment(new FoodDetailFragment(),bundle,"fooddetail");
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder{
            ImageButton img_food_fooditem;
            TextView tx_foodname_price_fooditem;
            TextView tx_intro_fooditem;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
               img_food_fooditem = itemView.findViewById(R.id.img_food_fooditem);
               tx_foodname_price_fooditem = itemView.findViewById(R.id.tx_foodname_price_fooditem);
               tx_intro_fooditem = itemView.findViewById(R.id.tx_intro_fooditem);

            }
        }
    }
    MyAdaper adaper;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_food_list, container, false);
        btn_back_head = view.findViewById(R.id.btn_back_head);
        btn_like_head = view.findViewById(R.id.btn_like_head);
        tx_shopname_head = view.findViewById(R.id.tx_shopname_head);
        rv_foodlist_center = view.findViewById(R.id.rv_foodlist_center);
        btn_cart = view.findViewById(R.id.btn_cart);
        context = this.getActivity();
        queue = Volley.newRequestQueue(context);
        manager = this.getActivity().getSupportFragmentManager();
        adaper = new MyAdaper();
        rv_foodlist_center.setAdapter(adaper);
        rv_foodlist_center.setLayoutManager(new LinearLayoutManager(context));
        //获取前一个页面传递的参数
        shop_id = this.getArguments().getInt("shop_id");
       String shopname = this.getArguments().getString("shopname");
       prePage = this.getArguments().getString("prePage");
       tx_shopname_head.setText(shopname);
       getArrayList(Utils.urlBase+"and_getFoodsByShopId.do?id="+shop_id);
       //设置返回按钮的点击事件
        btn_back_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(prePage.equals("shoplist")||prePage.equals("fooddetail")){
                    changeFragment(new ShopListFragment(),null,"shoplist");
                }
                else if(prePage.equals("shopcollect")) {
                    Bundle bundle = new Bundle();
                    bundle.putString("page","shop");
                    changeFragment(new CollectFragment(), bundle, "collectshop");
                }
            }
        });
        btn_cart.setOnClickListener(v ->{
            Bundle bundle = new Bundle();
            bundle.putInt("shop_id",shop_id);
            bundle.putString("shopname",shopname);
            bundle.putString("prePage","foodlist");
            changeFragment(new CartFragment(),bundle,"cart");
        });
        // 设置收藏按钮点击事件
        btn_like_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect collect = new Collect(0,
                        MainActivity.user_id,null,
                        shop_id,null,1,null,new Date(),0);
                        sendJSONObject(Utils.urlBase+"and_addCollect.do",collect);
            }
        });
        return view;
    }
    //获取网络图片
    public void getImageByURL(String url,ImageButton imageButton){
        int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
        int cachSize = maxMemory/8;
        LruCache<String, Bitmap> lruCache = new LruCache<String,Bitmap>(cachSize);
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String s) {
                return lruCache.get(s);
            }

            @Override
            public void putBitmap(String s, Bitmap bitmap) {
                lruCache.put(s,bitmap);
            }
        };
        ImageLoader loader = new ImageLoader(queue,imageCache);
        ImageLoader.ImageListener listener
                = ImageLoader.getImageListener(imageButton,
                R.drawable.ic_launcher_background,
                R.drawable.ic_launcher_foreground);
        loader.get(url,listener);
    }
    //获取网络数据
    public void getArrayList(String url){
        Response.Listener listener1 = new Response.Listener(){

            @Override
            public void onResponse(Object o) {
                list = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),new TypeToken<ArrayList<Food>>(){}.getType());
                adaper.notifyDataSetChanged();
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonArrayRequest(url,listener1,listener2);
        queue.add(request);
    }
    public void changeFragment(Fragment fragment,Bundle bundle,String tag){
        //清空子页面栈
        for(int i=0,count = manager.getBackStackEntryCount();i<count;i++){
            manager.popBackStack();
        }
        //创建一个子页面的事务，以便切换子页面
        FragmentTransaction transaction = manager.beginTransaction();
        //设置子页面的初始化参数
        fragment.setArguments(bundle);
        //切换子页面，让子页面显示到主页面的指定位置
        transaction.add(R.id.linear_fragment,fragment);
        //给栈中的子页面一个标签
        transaction.addToBackStack(tag);
        //提交事务
        transaction.commit();
    }
    public void sendJSONObject(String url,Collect collect)  {
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String msg = jsonObject.getString("msg");
                    Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(collect,Collect.class);
        try {
            JSONObject object = new JSONObject(s);
            JsonRequest request = new JsonObjectRequest(url,object,listener1,listener2);
            queue.add(request);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

}